package ext.csc.component.numbergen.number;

import ext.csc.component.numbergen.bean.PropertiesBean;

public class Sequence {
	private String value;
	private int iValue;
	
	public Sequence(PropertiesBean pb, FormatedNumber number){
		String seqFormat = pb.getSequenceFormat();
		int seqBeginAt = pb.getSequenceBeginAt();

		String seqClassPath = number.getClassification().getObjectclasspath();
		
		int iValue;
		iValue = getCancelledSequence(seqClassPath);
		if(iValue == -1){
			//Could not find the cancelled free seq
			iValue= getGeneratedSequence(seqClassPath);
			if(iValue == -1){
				//Could not find any request record before
				iValue = seqBeginAt;
			}else{
				iValue++;
			}
		}
		
		//If the value is not bigger than beginAt, set it to beginAt value
		//if(iValue < seqBeginAt) iValue = seqBeginAt;
		this.iValue = iValue;
		this.value = formatSequence(iValue,seqFormat);
	}
	
	/**
	 * Get the Min Sequence Number of the Cancelled Numbers
	 * @param classPath
	 * @return
	 */
	private int getCancelledSequence(String classPath){
		return NumberManager.getMaxSequence(classPath, NumberManager.CANCELLED_FLAG);
	}
/*	private int getCancelledSequence(String classPath){
		int result = 0;
		ArrayList aNumbers = NumberManager.getNumbersByClassPath(classPath, NumberManager.CANCELLED_FLAG, NumberManager.ASC);
		if(aNumbers.size() > 0){
			GeneratedNumber gNumber = (GeneratedNumber)aNumbers.get(0);
			result = gNumber.getSeq();
		}else{
			result = -1;
		}
		return result;
	}*/
	
	/**
	 * Get the Max Sequence Number of All Generated Numbers
	 * @param classPath
	 * @return
	 */
	
	private int getGeneratedSequence(String classPath){
		return NumberManager.getMaxSequence(classPath, NumberManager.ALL_FLAG);
	}
/*	private int getGeneratedSequence(String classPath){
		int result = 0;
		ArrayList aNumbers = NumberManager.getNumbersByClassPath(classPath, NumberManager.ALL_FLAG, NumberManager.DESC);
		if(aNumbers.size() > 0){
			GeneratedNumber gNumber = (GeneratedNumber)aNumbers.get(0);
			result = gNumber.getSeq();
		}else{
			result = -1;
		}
		return result;
	}*/
	
	/**
	 * Format the int value of sequence to specified '###' which is defined on properties file
	 * @param value
	 * @param seqFormat
	 * @return
	 */
	private String formatSequence(int value, String seqFormat){
		String result;
		
		int seqFormatLength = seqFormat.length();
		String seqlValue = String.valueOf(value);
		
		seqFormat = seqFormat.replace('#', '0');
		
		result = right((seqFormat + seqlValue),seqFormatLength);
		
		return result;
	}
	
	  private static String right(String s,int pos){
          String dido = new StringBuffer(s).reverse().substring(0,pos);   
          StringBuffer sb = new StringBuffer(dido).reverse();   
          String didoleo = new String(sb);   
          return didoleo;   
	  }

	public int getIValue() {
		return iValue;
	}

	public String getValue() {
		return value;
	}   

}
